<?php
/**
 * Class Infrastructure_Mapper_Timelog
 */
class Infrastructure_Mapper_Timelog extends Infrastructure_Mapper_AbstractBase
{
    /**
     * @param int $id
     * @return stdClass
     */
    public function findOneByById($id)
    {
        $query = "SELECT * FROM `log` WHERE `id`=:id";
        $res = $this->query($query, array('id' => $id));
        return $res->fetchObject();
    }

    /**
     * @return array
     */
    public function findLatestRecords()
    {
        $query = "SELECT * FROM `log` ORDER BY `date` DESC LIMIT 30";
        $res = $this->query($query);
        return $res->fetchAll(PDO::FETCH_OBJ);
    }

    /**
     * @param string $time
     * @param int $id
     */
    public function updateStartById($time, $id)
    {
        $query = "UPDATE `log` SET `start`=:time WHERE `id`=:id";
        $this->query($query, array('time' => $time, 'id' => $id));
    }

    /**
     * @param string $time
     * @param int $id
     */
    public function updateLunchById($time, $id)
    {
        $query = "UPDATE `log` SET `lunch`=:time WHERE `id`=:id";
        $this->query($query, array('time' => $time, 'id' => $id));
    }

    /**
     * @param string $time
     * @param int $id
     */
    public function updateLunchEndById($time, $id)
    {
        $query = "UPDATE `log` SET `lunchend`=:time WHERE `id`=:id";
        $this->query($query, array('time' => $time, 'id' => $id));
    }

    /**
     * @param string $time
     * @param int $id
     */
    public function updateEndById($time, $id)
    {
        $query = "UPDATE `log` SET `end`=:time WHERE `id`=:id";
        $this->query($query, array('time' => $time, 'id' => $id));
    }

    /**
     * @param int $id
     */
    public function calculateOvertimeById($id)
    {
        $row = $this->findOneByById($id);
        $endStartDiff = strtotime($row->end) - strtotime($row->start);
        $lunchEndLunchDiff = strtotime($row->lunchend) - strtotime($row->lunch);
        $workTime = $endStartDiff - $lunchEndLunchDiff - (8 * 3600);

        if ($workTime < 0) {
            $workTime = 0;
        }

        $query = "UPDATE `log` SET `overtime`=:overtime WHERE `id`=:id";
        $this->query($query, array('overtime' => gmdate("H:i:s", $workTime), 'id' => $id));
    }

    /**
     * @param string $date
     * @return stdClass
     */
    public function findOneByByDate($date)
    {
        $query = "SELECT * FROM `log` WHERE `date`=:date";
        $res = $this->query($query, array('date' => $date));
        return $res->fetchObject();
    }

    /**
     * @param string $date
     */
    public function createNewEntryWithDate($date)
    {
        $id = $this->getNewId('id', 'log');
        $query = "INSERT INTO `log` (`id`, `date`) VALUES (:id, :date)";
        $this->query($query, array('id' => $id, 'date' => $date));
    }
}
